<template>
  <div class="clerkDoc">
    <div class="operation">
      <el-button type="primary" icon="el-icon-plus" @click="newClerk"
        >新建</el-button
      >
      <el-button icon="el-icon-delete" @click="deleteClerk">删除</el-button>
      <el-button @click="exportExcel" icon="el-icon-upload2">导出</el-button>
    </div>
    <el-table
      :data="clerkData"
      id="outTable"
      :default-sort="{ prop: 'no', order: 'default-sort' }"
      highlight-current-row
      height="80vh"
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
      @row-click="rowClick"
      @row-dblclick="dblclick"
    >
      <el-table-column prop="no" label="编号" width="80"></el-table-column>
      <el-table-column prop="name" label="职员" width="160"></el-table-column>
      <el-table-column
        prop="department"
        label="部门"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="phone"
        label="联系方式"
        width="160"
      ></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="vx" label="微信"></el-table-column>
      <el-table-column
        prop="warehouseNo"
        label="仓库编号"
        width="160"
      ></el-table-column>
    </el-table>
    <foot-view
      class="footView"
      :pagesNum="pagesNum"
      :hasPagination="true"
      :pageSize="limit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
      <div slot="text">
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>
    <div class="mask" :style="{ display: showNewClerk }"></div>
    <div class="newClerk" :style="{ display: showNewClerk }">
      <div class="nc-top">
        <p>{{ isNew }}职员</p>
        <i class="el-icon-close" @click="closeNewClerk"></i>
      </div>
      <div class="clerkInfo">
        <div class="inp-1">
          <p><span>*</span>编号</p>
          <el-input class="kd" type="text" v-model="no"></el-input>
          <p><span>*</span>职员</p>
          <el-input class="kd" type="text" v-model="name"></el-input>
        </div>
        <div class="inp-1">
          <p><span>*</span>仓库</p>
          <el-input
            type="text"
            style="width: 60px; margin-right: 10px"
            v-model="warehouseNo"
            @blur="houseId"
          ></el-input>
          <el-select
            v-model="warehouseName"
            @change="houseName"
            style="width: 100px"
          >
            <el-option
              v-for="item in warehouseIdList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <p><span>*</span>部门</p>
          <el-select v-model="department" class="kd">
            <el-option
              v-for="item in this.dList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div class="inp-1">
          <p>微信</p>
          <el-input class="kd" type="text" v-model="vx"></el-input>
          <p>联系方式</p>
          <el-input class="kd" v-model="phone"></el-input>
        </div>
        <div class="inp-1">
          <p>地址</p>
          <el-input
            style="width: 435px"
            type="text"
            v-model="address"
          ></el-input>
        </div>
        <div class="inp-1">
          <p>备注</p>
          <el-input
            class="kd"
            v-model="remark"
            @keyup.enter.native="saveClerk"
          ></el-input>
          <!-- <p>部门主管</p>
          <el-switch style="margin-top:2px;" v-model="isPrincipal"></el-switch> -->
        </div>
      </div>
      <el-button type="primary" @click="saveClerk">保存</el-button>
    </div>
  </div>
</template>

<script>
import footView from '../../../components/FootView'
import {
  getClerk,
  getDepartmentList,
  addClerk,
  delClerk,
  update
} from '../../../network/clerk'
import { getWarehouse } from '../../../network/warehouse'
import { getRoleList } from '../../../network/department'

import XLSX from 'xlsx'
import FileSaver from 'file-saver'

import enterUp from '../../../components/mixins/enterUp'
import outex from '../../../components/mixins/outexp'

export default {
  name: 'clerk_doc',
  mixins: [enterUp, outex],
  created() {
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null

    this.inpList = this.getInput()
    //获取仓库
    getWarehouse().then((res) => {
      res.data.data.forEach((element) => {
        this.warehouseIdList.push({ value: element.no, label: element.name })
        if (element.isMainWarehouse == 1) {
          this.warehouseNo = element.no
          this.warehouseName = element.name
        }
      })
    })

    this._getClerk()
    // this._getRoleList()
  },
  data() {
    return {
      inpList: [],
      departmentName: '',
      dList: [],
      // 总数据条数
      dataLen: 0,
      // 总页码
      pagesNum: 0,
      // 分页条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      clerkData: [],
      showNewClerk: 'none',
      no: '',
      id: '',
      warehouseNo: '',
      warehouseName: '',
      warehouseIdList: [],
      department: '',
      departmentList: [],
      vx: '',
      address: '',
      name: '',
      phone: '',
      remark: '',
      // isPrincipal:false,
      jxQuarter: null,
      // jxQuarter: document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))[1],

      detail: {},
      isNew: '新建'
    }
  },
  watch: {
    dataLen(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    },
    limit(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    },
    no(a, b) {
      this.no = a.toUpperCase().trim()
    },
    name(a, b) {
      this.name = a.toUpperCase().trim()
    }
  },
  components: {
    footView
  },
  methods: {
    _getRoleList() {
      getRoleList().then((res) => {
        this.dList = []
        res.data.data.forEach((e) => {
          this.dList.push({ value: e.roleName, label: e.roleName })
        })
        // console.log(this.dList, 'dList')
      })
    },
    // 显示仓库
    houseId() {
      if (!this.warehouseNo) {
        this.warehouseName = ''
        return
      }
      for (const i of this.warehouseIdList) {
        if (this.warehouseNo == i.value) {
          this.warehouseName = i.label
          return
        }
      }
      this.$message.error('无此仓库编号')
      this.warehouseNo = ''
      this.warehouseName = ''
    },
    houseName(e) {
      this.warehouseNo = e
    },

    rowClick(e) {
      this.id = e.id
    },
    dblclick(row) {
      // console.log(row)
      this.detail = row
      this.isNew = '编辑'
      this.showNewClerk = 'block'

      this.no = this.detail.no
      this.name = this.detail.name
      this.warehouseNo = this.detail.warehouseNo
      this.department = this.detail.department
      this.vx = this.detail.vx
      this.phone = this.detail.phone
      this.remark = this.detail.remark
      this.address = this.detail.address
      this.isPrincipal = this.detail.isPrincipal ? true : false
    },
    newClerk() {
      this.id = ''
      this.isNew = '新建'
      this.showNewClerk = 'block'
      this.no = ''
      this.name = ''
      this.department = ''
      this.vx = ''
      this.phone = ''
      this.address = ''
      this.remark = ''
      this.isPrincipal = false

      this._getRoleList()
    },

    closeNewClerk() {
      this.showNewClerk = 'none'
    },
    saveClerk() {
      if (this.no == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '编号不能为空'
        })
        return
      }
      if (this.warehouseNo == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '仓库不能为空'
        })
        return
      }
      if (this.name == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '职员不能为空'
        })
        return
      }
      if (this.department == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '部门不能为空'
        })
        return
      }
      if (this.isNew == '新建') {
        let params = {
          no: this.no,
          warehouseNo: this.warehouseNo,
          name: this.name,
          department: this.department,
          vx: this.vx,
          phone: this.phone,
          address: this.address,
          remark: this.remark,
          isPrincipal: 0
        }
        addClerk(params).then((res) => {
          console.log(res)
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              offset: 400,
              message: '添加成功'
            })

            this._getClerk()
          } else {
            this.$message.error({
              offset: 400,
              message: '添加失败'
            })
          }
          this.showNewClerk = 'none'
        })
      } else {
        this.detail.no = this.no
        this.detail.name = this.name
        this.detail.warehouseNo = this.warehouseNo
        this.detail.department = this.department
        this.detail.vx = this.vx
        this.detail.phone = this.phone
        this.detail.address = this.address
        this.detail.remark = this.remark
        // this.detail.isPrincipal = this.isPrincipal ? 1 : 0
        update(this.detail).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              offset: 400,
              message: '修改成功'
            })
            this._getClerk()
          } else {
            this.$message.error({
              offset: 400,
              message: '修改失败'
            })
          }
          this.showNewClerk = 'none'
        })
      }
    },
    deleteClerk() {
      if (this.id == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '请选择要删除的数据'
        })
        return
      }
      this.$confirm('是否删除此职员的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delClerk({
            id: this.id
          }).then((res) => {
            if (res.data.code == 200) {
              this.dataLen--
              this._getClerk()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 请求数据
    _getClerk() {
      getClerk({ limit: this.limit, page: this.currentPage }).then((res) => {
        this.clerkData = res.data.data || []
        this.dataLen = res.data.total
        this.id = ''
      })
    },

    // 每页显示页数改变
    handleSizeChange(val) {
      this.limit = val
      this._getClerk()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this._getClerk()
    },

    exportExcel() {
      if (!this.clerkData.length) return
      getClerk({ limit: 9999, page: 1 }).then((res) => {
        let list = []
        res.data.data.forEach((e) => {
          list.push({
            编号: e.no,
            职员: e.name,
            部门: e.department,
            联系方式: e.phone,
            地址: e.address,
            备注: e.remark,
            微信: e.vx,
            仓库编号: e.warehouseNo
          })
        })
        let wb = {
          SheetNames: ['sheet1'],
          Sheets: {
            sheet1: XLSX.utils.json_to_sheet(list)
          }
        }
        // console.log(wb)
        let wbout = XLSX.write(wb, {
          bookType: 'xlsx',
          bookSST: true,
          type: 'array'
        })
        try {
          FileSaver.saveAs(
            new Blob([wbout], {
              type: 'application/octet-stream;charset=utf-8'
            }),
            '职员表.xlsx'
          )
          this.$emit('exportFinish')
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout)
        }
        return wbout
      })
    }
  }
}
</script>

<style scoped>
.clerkDoc {
  margin-right: 0.5vw;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}

/* 按钮 */
.operation {
  padding: 15px 0;
  border-bottom: 2px solid #f4f4f4;
  margin-bottom: 15px;
}

.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.inp-1 span {
  color: red;
}
.inp-1 {
  margin-bottom: 10px;
}

.mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.3;
  z-index: 9;
}
.newClerk {
  position: fixed;
  top: 25%;
  left: 50%;
  transform: translateX(-50%);
  background-color: #fff;
  width: 570px;
  height: 275px;
  box-sizing: border-box;
  z-index: 99;
}
.nc-top {
  background-color: #f2f2f2;
  height: 50px;
  margin-bottom: 15px;
}
.nc-top p {
  float: left;
  margin: 15px 0 0 20px;
  font-weight: bolder;
}
.nc-top i {
  width: 50px;
  float: right;
  text-align: center;
  line-height: 50px;
}
.kd {
  width: 170px;
}
.clerkInfo p {
  display: inline-block;
  width: 75px;
  margin: 2px 6px 0 0;
  text-align: right;
  margin: 0 10px;
}
.clerkInfo > div:last-child p {
  display: inline-block;
}
.clerkInfo .el-button {
  position: relative;
  bottom: 0;
  right: 0;
}
</style>

<style>
.clerkInfo .el-input__inner {
  height: 30px;
}
.newClerk .el-button {
  position: absolute;
  bottom: 16px;
  right: 16px;
}
.clerkDoc .el-button {
  padding: 8px 15px;
  margin-right: 12px;
  height: 30px;
}
.clerkDoc .el-button + .el-button {
  margin-left: 0;
}
.clerkDoc .el-input__icon {
  line-height: 30px;
}
</style>
